<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" @submit.native.prevent>
      <el-form-item label="商家名称">
        <el-input size="small" v-model="listQuery.q_sellerName"></el-input>
      </el-form-item>
      <!-- <el-form-item label="用户名">
        <el-input size="small" v-model="listQuery.q_name"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select class="toolbar-lable-right" size="small" v-model="listQuery.q_auditStatus" placeholder="请选择">
          <el-option v-for="item in optStateValues" :key="item.value" :label="item.name" :value="item.value"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="this.getList">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
        <el-button size="small" type="primary" @click="append">新增商家</el-button>
      </el-form-item>
    </el-form>
    <!-- <div class="button-table-margin">
      <el-button size="small" type="primary" @click="deactivate">停用</el-button>
      <el-button size="small" type="primary" @click="enable">启用</el-button>
      <el-button size="small" type="primary" @click="applyments">申请微信二级商户</el-button>
      <el-button size="small" type="primary" @click="applymentsAli">申请支付宝二级商户</el-button>
    </div> -->

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="`启用(${enableCount})`"  name="first"></el-tab-pane>
      <el-tab-pane :label="`禁用(${disableCount})`"  name="second"></el-tab-pane>
    </el-tabs>
    <el-table
      ref="singleTable"
      :data="dataList"
      v-loading="listLoading"
      border
      fit
      highlight-current-row
      tooltip-effect="dark"
      style="width: 100%"
      @current-change="handleCurrentChange">
      <el-table-column type="index" align="center" width="50"></el-table-column>
      <el-table-column width="120" show-overflow-tooltip property="name" label="账号"></el-table-column>
      <el-table-column show-overflow-tooltip width="160" property="sellerName" label="商家名称"></el-table-column>
      <!-- <el-table-column width="120" property="sellerName" label="申请店铺名"></el-table-column> -->
      <el-table-column width="120" property="status" label="商家状态">
        <template slot-scope="scope">
          {{
            scope.row.status == 0 ? "禁用" : "启用"
          }}
        </template>
      </el-table-column>
      <el-table-column width="200" property="bussinessLicense" label="营业执照编号">
      </el-table-column>
      <el-table-column width="200" property="taxLicense" label="统一社会信用代码">
      </el-table-column>
      <el-table-column width="160" property="telephone" label="联系电话">
      </el-table-column>
      <el-table-column show-overflow-tooltip width="200" property="companyAdd" label="地址">
      </el-table-column>
      <!-- <el-table-column width="200" property="organization" label="组织机构代码">
      </el-table-column> -->
      <el-table-column property="legalPerson" label="法人"> </el-table-column>
      <el-table-column width="160" property="personPhone" label="法人电话">
      </el-table-column>
      <el-table-column width="160" property="companyStartTime" label="营业开始时间"> </el-table-column>
      <el-table-column width="160" property="companyEndTime" label="营业结束时间"> </el-table-column>

      <el-table-column width="160" property="createTime" label="创建时间">
      </el-table-column>
      <!-- <el-table-column property="sellerGrade" label="店铺等级"></el-table-column>
      <el-table-column property="scoreService" label="服务评分"></el-table-column>
      <el-table-column property="scoreDeliverGoods" label="发货评分"></el-table-column>
      <el-table-column property="scoreDescription" label="描述评分"></el-table-column>
      <el-table-column property="productNumber" label="商品数量"></el-table-column>
      <el-table-column width="120" property="collectionNumber" label="被收藏数量"></el-table-column>
      <el-table-column width="120" property="saleMoney" label="店铺总销售金额"></el-table-column>

      <el-table-column property="orderCount" label="总订单量"></el-table-column>
      <el-table-column width="120" property="orderCountOver" label="完成订单量"></el-table-column>
      <el-table-column width="180" property="wxRequestNo" label="微信申请编号"></el-table-column>
      <el-table-column width="180" property="wxApplymentId" label="微信返回申请编号"></el-table-column>
      <el-table-column width="120" property="subMchid" label="微信进件状态">
        <template slot-scope="scope">
          {{
            scope.row.wxRequestNo == "" || scope.row.wxRequestNo == null
              ? "未提交进件"
              : scope.row.applymentState == "" || scope.row.applymentState == null
              ? "已提交请等待"
              : scope.row.applymentState == "AUDITING"
              ? "审核中"
              : scope.row.applymentState == "NEED_SIGN"
              ? "待签约"
              : scope.row.applymentState == "FINISH"
              ? "完成"
              : "驳回"
          }}
        </template>
      </el-table-column>
      <el-table-column width="120" show-overflow-tooltip property="signUrl" label="微信签约地址">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.signUrl }}</p>
            <div slot="reference" class="name-wrapper">
              <p>{{ scope.row.signUrl }}</p>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column width="120" show-overflow-tooltip property="rejected" label="微信驳回原因">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.rejected }}</p>
            <div slot="reference" class="name-wrapper">
              <p>{{ scope.row.rejected }}</p>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column width="120" property="subMchid" label="微信二级商户号"></el-table-column>
      <el-table-column width="120" property="aliSignUrl" label="支付宝进件状态">
        <template slot-scope="scope">
          {{
            scope.row.aliSignUrl == "" || scope.row.aliSignUrl == null
              ? "未提交进件"
              : scope.row.aliSignUrl == "CREATE"
              ? "已发起二级商户确认"
              : scope.row.aliSignUrl == "SKIP"
              ? "无需确认"
              : scope.row.aliSignUrl == "FAIL"
              ? "签约失败"
              : scope.row.aliSignUrl == "NOT_CONFIRM"
              ? "商户未确认"
              : "签约完成"
          }}
        </template>
      </el-table-column>
      <el-table-column width="140" property="aliSubMchid" label="支付宝二级商户号"></el-table-column>
      <el-table-column width="120" show-overflow-tooltip property="aliRejected" label="支付宝驳回原因">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.aliRejected }}</p>
            <div slot="reference" class="name-wrapper">
              <p>{{ scope.row.aliRejected }}</p>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ codeBox.SELLER_AUDIT_STATE[scope.row.auditStatus] }}
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewDetails(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleConfig(scope.row)"
          >配置</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          >编辑</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleStatus(scope.row)"
          >{{ scope.row.status == 0 ? '启用' : '停用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog
      :title="status === 0 ? '启用商家' : '禁用商家'"
      :visible.sync="dialogVisible"
      width="30%">
      <span>确定{{ status === 0 ? '启用' : '禁用' }}商家「{{sellerName }}」吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateStatus">确 定</el-button>  
      </span>
    </el-dialog>

  </div>
</template>
<script>
import { getCodeManager, codeToArray } from "@/api/all";
import { manageListSeller, freezeManageSeller, unfreezeManageSeller, sellerApplyments, sellerApplymentsAli, updateStatus, queryCount } from "@/api/seller";
import Pagination from "@/components/Pagination";
import { Message } from "element-ui";
export default {
  name: "sellerSetting",
  components: { Pagination },
  data() {
    return {
      enableCount: 0,
      disableCount: 0,
      status: 0,
      sellerName: "",
      sellerId: "",
      dialogVisible: false,
      activeName: 'first',
      dataList: [],
      optStateValues: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        q_sellerName: "",
        q_auditStatus: "",
        q_name: "",
        q_status: 1,
      },
      currentRow: null,
    };
  },
  created() {
    // 状态
    getCodeManager("SELLER_AUDIT_STATE", () => {
      this.optStateValues = codeToArray("SELLER_AUDIT_STATE");
    });
    // 列表状态
    getCodeManager("SELLER_AUDIT_STATE", () => {});
    this.getList();
    this.querySellerCount();
  },
  methods: {
    handleStatus(row) {
      this.dialogVisible = true
      this.status = row.status,
      this.sellerName = row.sellerName,
      this.sellerId = row.id
    },
    updateStatus() {
      const newStatus = this.status == 0 ? 1 : 0;
      const seller = {
        id: this.sellerId,
        status: newStatus
      };
      // 这里可以调用API更新状态
      updateStatus(seller).then((rsp) => {
        if(rsp.code == 200) {
          this.$message.success(`已${newStatus == 0 ? '启用' : '停用'}`);
        }
        this.dialogVisible = false
        getList();
      }).catch(error => {
        this.$message.error('操作失败');
      });
    },
    handleClick(tab) {
      console.log(tab);
      if (tab.name === 'first') {
        this.listQuery.q_status = 1;
      } else if (tab.name === 'second') {
        this.listQuery.q_status = 0;
      }
      this.querySellerCount();
      this.getList();
    },
    querySellerCount(){
      const countQuery = {
        "q_sellerName" : this.listQuery.q_sellerName,
      }
      queryCount(countQuery).then((res) => {
        console.log(res);
        if (res.data.data) {
          this.enableCount = res.data.data.enableCount;
          this.disableCount = res.data.data.disableCount;
        }
      });
    },
    getList() {
      this.listLoading = true;
      manageListSeller(this.listQuery).then((res) => {
        this.dataList = res.data.rows;
        this.total = res.data.total;
        this.listLoading = false;
      });
    },
    append() {
      this.$router.push({ path: '/seller/sellerapplyadd' })
    },
    handleConfig(row){
      console.log("行数据", row);
      this.$router.push({ path: '/seller/sellerconfig', query: { sellerId: row.id , sellerName: row.sellerName } })
    },
    viewDetails(row) {
      this.currentRow = row;
      // 查看详情
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      this.$router.push({ path: '/seller/sellerapplyaudit', query:{id: this.currentRow.id} })
    },
    edit(row) {
      this.currentRow = row;
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      this.$router.push({ path: '/seller/sellerapplyedit', query: { id: this.currentRow.id } })
    },
    handleCurrentChange(val) {
      // 选中当前行数据
      this.currentRow = val;
    },
    applymentsAli(id) {
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      let currentId = this.currentRow.id;
      if (this.currentRow.aliSubMchid != "" && this.currentRow.aliSubMchid != null) {
        Message.error("商家已成为支付宝二级商户");
        return;
      }
      if (this.currentRow.aliRequestNo != "" && this.currentRow.aliRequestNo != null) {
        Message.error("该商家已申请，请等待审核结果");
        return;
      }
      if (this.currentRow.auditStatus != "2") {
        Message.error("只有审核通过的商家可申请");
        return;
      }
      this.$confirm("确定为商家申请成为支付宝二级商户吗?", "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          sellerApplymentsAli({ sellerId: currentId }).then((res) => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消申请",
          });
        });
    },
    applyments(id) {
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      let currentId = this.currentRow.id;
      if (
        this.currentRow.subMchid != "" &&
        this.currentRow.subMchid != null &&
        this.currentRow.aliSubMchid != "" &&
        this.currentRow.aliSubMchid != null
      ) {
        Message.error("商家已成为二级商户");
        return;
      }
      if (
        this.currentRow.wxRequestNo != "" &&
        this.currentRow.wxRequestNo != null &&
        this.currentRow.aliRequestNo != "" &&
        this.currentRow.aliRequestNo != null
      ) {
        Message.error("该商家已申请，请等待审核结果");
        return;
      }
      if (this.currentRow.auditStatus != "2") {
        Message.error("只有审核通过的商家可申请");
        return;
      }
      this.$confirm("确定为商家申请成为二级商户吗?", "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          sellerApplyments({ sellerId: currentId }).then((res) => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消申请",
          });
        });
    },
    deactivate(id, status) {
      let [currentId, currentStatus] = ["", ""];
      if (id > 0) {
        currentId = id;
        currentStatus = status;
      } else {
        // 停用
        if (!this.currentRow) {
          Message.error("请选择数据");
          return;
        }
        currentId = this.currentRow.id;
        currentStatus = this.currentRow.auditStatus;
      }
      if (currentStatus != 2) {
        Message.error("只有审核通过状态才能被冻结");
        return;
      }
      this.$confirm("确定停用该商家吗？停用后，该商家的店铺及所有商品将被冻结", "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          freezeManageSeller({ sellerId: currentId }).then((res) => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消冻结",
          });
        });
    },
    enable(id, status) {
      // 启用
      let [currentId, currentStatus] = ["", ""];
      if (id > 0) {
        currentId = id;
        currentStatus = status;
      } else {
        if (!this.currentRow) {
          Message.error("请选择数据");
          return;
        }
        currentId = this.currentRow.id;
        currentStatus = this.currentRow.auditStatus;
      }
      if (currentStatus != 3) {
        Message.error("只有冻结状态才能被解冻");
        return;
      }
      this.$confirm("确定解冻该商家吗？", "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          unfreezeManageSeller({ sellerId: currentId }).then((res) => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消解冻",
          });
        });
    },
    reset() {
      this.listQuery.q_sellerName = "";
      this.listQuery.q_auditStatus = "";
      this.listQuery.q_name = "";
      this.getList();
    },
  },
};
</script>
